/*
* SMILParser
*
* Version 1.0
*
* Programmers: Jesse Louderback, Noah Pham, Chad Carpenter, and Marc Hindman
*/
package com.SmilDial;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import comm.SMS_Sender;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class InboxMenu extends Activity {
	ArrayList<String> listOfMessages;
	ArrayAdapter<String> imgAdapter;
	ListView myImageList;
	protected final static String FILE_LOC = 
			Environment.getExternalStorageDirectory().getAbsolutePath() + "/SMIL Messages/";
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inbox_menu); 
        
        File directoryExist = new File(Environment.getExternalStorageDirectory()
        							   + "/SMIL Messages");        
        
        if (!(directoryExist.isDirectory())) {
        	File sdCard = Environment.getExternalStorageDirectory();
        	File dir = new File (sdCard.getAbsolutePath() + "/SMIL Messages"); 
			dir.mkdirs();
        }       
        
        populateMessageList();  
    }
    
    private void populateMessageList() {
    	 listOfMessages = getListOfMessages();
         myImageList = (ListView)findViewById(R.id.inboxListView);
         imgAdapter  = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
        		 								listOfMessages);     
         myImageList.setAdapter(imgAdapter); 
         
         myImageList.setOnItemClickListener(new OnItemClickListener() {
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
             	 String message = ((TextView)view).getText().toString(); 
             	
             	 Intent intent = new Intent(InboxMenu.this, ViewMessage.class);
             	 intent.putExtra("file", message);
             	 startActivity(intent);                
             }
         });
         registerForContextMenu(myImageList);
    }
    
    @Override  
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {       	    
     	menu.setHeaderTitle("Message Options");   
        menu.add(0, v.getId(), 0, "Forward");   
        menu.add(0, v.getId(), 0, "Delete");    
    }  
    
    @Override
    public boolean onContextItemSelected(MenuItem item) { 
    	  String selectedOption = item.getTitle().toString();
    	  //Convert the Array<String> to a regular String array
    	  final String[] convertedListOfImages = 
    			  listOfMessages.toArray(new String[listOfMessages.size()]);   
    	  AdapterView.AdapterContextMenuInfo info = 
    			  (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    	  String listItemName =  convertedListOfImages[info.position];
    	  
    	  if (selectedOption == "Forward") {
    		  final String fileMessage = getMessageFromFile(listItemName).toString();
    		  
    		  AlertDialog.Builder alert = new AlertDialog.Builder(this);

    		  alert.setTitle("Forward Message");
    		  alert.setMessage("Input Phone Number");

    		  // Set an EditText view to get user input 
    		  final EditText input = new EditText(this);
    		  alert.setView(input);

    		  alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    			  public void onClick(DialogInterface dialog, int whichButton) {} //Do Nothing
      		  });
    		  
    		  alert.setPositiveButton("Send", new DialogInterface.OnClickListener() {
	    		  public void onClick(DialogInterface dialog, int whichButton) {
	    			  String phoneNo = input.getText().toString();
	    		    
	    		      if (phoneNo.length() > 0) {
						  SMS_Sender send = new SMS_Sender();
						  send.sendSMS(getApplicationContext(), phoneNo, fileMessage);
					  }
	    		  }
    		  });

    		  alert.show();
    	  } else if (selectedOption == "Delete") {
        	  removeMessageFromPhone(listItemName);
        	  imgAdapter.notifyDataSetInvalidated();
        	  populateMessageList();
    	  }
    	  
    	  return true;
    }
    
    private StringBuilder getMessageFromFile(String fileName) {    
        File fileExist = new File(Environment.getExternalStorageDirectory() + 
        						  "/SMIL Messages/" + fileName);
        StringBuilder fileMessage = new StringBuilder();
        
        if (fileExist.exists()) {
        	try {     
        		BufferedReader myBufferedReader = new BufferedReader(
        				new FileReader(Environment.getExternalStorageDirectory() 
        							   + "/SMIL Messages/" + fileName));     
        		String line;      
        		
        		while ((line = myBufferedReader.readLine()) != null) {         
        			fileMessage.append(line);         
        			fileMessage.append('\n');     
        		} 
        	} 
        	catch (IOException e) {             		
        		Toast toast = Toast.makeText(this, 
        				"There was an error in reading the SMIL file.", 2000); 
        		toast.show(); 
        	}        	
        }
        return fileMessage;
    }
    
	private void removeMessageFromPhone(String filename) {		 
		 File file = new File(FILE_LOC + filename);
		 file.delete();
	}
	
	private ArrayList<String> getListOfMessages() {
		FilenameFilter smilFilter = new FilenameFilter() {     
    		File f;     
    		public boolean accept(File dir, String name) {     
    			if(name.endsWith(".smil") || name.endsWith(".smil")) {             
    				return true;
    			}         
    			f = new File(dir.getAbsolutePath()+"/"+name);          
    			return f.isDirectory();     
    			}
    	};
		File dir = new File(FILE_LOC);
        File[] messageList = dir.listFiles(smilFilter);
        
        ArrayList<String> messages = new ArrayList<String>();           
        
        for (int i = 0; i < messageList.length; i++) {
        	messages.add(messageList[i].getName());
        }
        
		return messages;
	}
}